package com.example.managemyself.ui.health;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.cardview.widget.CardView;

import com.example.managemyself.R;
import com.example.managemyself.util.WhiteNoisePlayer;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Locale;

/**
 * 冥想功能Fragment
 * 提供冥想计时器和白噪音播放功能
 */
public class MeditationFragment extends Fragment implements WhiteNoisePlayer.PlaybackListener {
    
    private static final String TAG = "MeditationFragment";
    
    // UI组件
    private CardView cardMeditationTimer;
    private TextView tvMeditationTime;
    private TextView tvMeditationStatus;
    private ImageView ivBreathingGuide;
    private FloatingActionButton fabStartPause;
    private Button btnStop;
    private SeekBar seekBarTimer;
    private TextView tvTimerDuration;
    
    private CardView cardWhiteNoise;
    private Spinner spinnerNoiseType;
    private Button btnPlayPause;
    private Button btnStopNoise;
    private SeekBar seekBarVolume;
    private TextView tvVolumeLevel;
    private TextView tvNoiseStatus;
    
    private CardView cardBreathingExercise;
    private TextView tvBreathingInstruction;
    private Button btnStartBreathing;
    private ImageView ivBreathingAnimation;
    
    // 计时器相关
    private CountDownTimer meditationTimer;
    private long meditationDurationMs;
    private long remainingTimeMs;
    private boolean isTimerRunning;
    private boolean isTimerPaused;
    
    // 白噪音播放器
    private WhiteNoisePlayer whiteNoisePlayer;
    
    // 呼吸练习相关
    private CountDownTimer breathingTimer;
    private boolean isBreathingActive;
    private int breathingCycle; // 0: 吸气, 1: 屏息, 2: 呼气, 3: 休息
    private ValueAnimator breathingAnimator;
    
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_meditation, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        setupMeditationTimer();
        setupWhiteNoise();
        setupBreathingExercise();
        initializeDefaults();
    }
    
    private void initViews(View view) {
        // 冥想计时器
        cardMeditationTimer = view.findViewById(R.id.card_meditation_timer);
        tvMeditationTime = view.findViewById(R.id.tv_meditation_time);
        tvMeditationStatus = view.findViewById(R.id.tv_meditation_status);
        ivBreathingGuide = view.findViewById(R.id.iv_breathing_guide);
        fabStartPause = view.findViewById(R.id.fab_start_pause);
        btnStop = view.findViewById(R.id.btn_stop);
        seekBarTimer = view.findViewById(R.id.seekbar_timer);
        tvTimerDuration = view.findViewById(R.id.tv_timer_duration);
        
        // 白噪音播放器
        cardWhiteNoise = view.findViewById(R.id.card_white_noise);
        spinnerNoiseType = view.findViewById(R.id.spinner_noise_type);
        btnPlayPause = view.findViewById(R.id.btn_play_pause);
        btnStopNoise = view.findViewById(R.id.btn_stop_noise);
        seekBarVolume = view.findViewById(R.id.seekbar_volume);
        tvVolumeLevel = view.findViewById(R.id.tv_volume_level);
        tvNoiseStatus = view.findViewById(R.id.tv_noise_status);
        
        // 呼吸练习
        cardBreathingExercise = view.findViewById(R.id.card_breathing_exercise);
        tvBreathingInstruction = view.findViewById(R.id.tv_breathing_instruction);
        btnStartBreathing = view.findViewById(R.id.btn_start_breathing);
        ivBreathingAnimation = view.findViewById(R.id.iv_breathing_animation);
    }
    
    private void setupMeditationTimer() {
        // 设置计时器SeekBar (5-60分钟)
        seekBarTimer.setMax(55); // 0-55, 对应5-60分钟
        seekBarTimer.setProgress(15); // 默认20分钟
        updateTimerDuration(20);
        
        seekBarTimer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && !isTimerRunning) {
                    int minutes = progress + 5;
                    updateTimerDuration(minutes);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        // 开始/暂停按钮
        fabStartPause.setOnClickListener(v -> {
            if (!isTimerRunning) {
                startMeditationTimer();
            } else if (isTimerPaused) {
                resumeMeditationTimer();
            } else {
                pauseMeditationTimer();
            }
        });
        
        // 停止按钮
        btnStop.setOnClickListener(v -> stopMeditationTimer());
    }
    
    private void setupWhiteNoise() {
        // 初始化白噪音播放器
        whiteNoisePlayer = WhiteNoisePlayer.getInstance(requireContext());
        whiteNoisePlayer.setPlaybackListener(this);
        
        // 设置噪音类型选择器 - 现在只有雨声一种
        String[] noiseNames = {"雨声"};
        
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, noiseNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerNoiseType.setAdapter(adapter);
        spinnerNoiseType.setSelection(0); // 默认选择雨声
        
        // 播放/暂停按钮
        btnPlayPause.setOnClickListener(v -> {
            if (whiteNoisePlayer.isPlaying()) {
                whiteNoisePlayer.pause();
            } else if (whiteNoisePlayer.getCurrentState() == WhiteNoisePlayer.PlayState.PAUSED) {
                whiteNoisePlayer.resume();
            } else {
                whiteNoisePlayer.play();
            }
        });
        
        // 停止按钮
        btnStopNoise.setOnClickListener(v -> whiteNoisePlayer.stop());
        
        // 音量控制
        seekBarVolume.setMax(100);
        seekBarVolume.setProgress(70); // 默认70%音量
        updateVolumeLevel(0.7f);
        
        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    float volume = progress / 100.0f;
                    whiteNoisePlayer.setVolume(volume);
                    updateVolumeLevel(volume);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    private void setupBreathingExercise() {
        btnStartBreathing.setOnClickListener(v -> {
            if (!isBreathingActive) {
                startBreathingExercise();
            } else {
                stopBreathingExercise();
            }
        });
    }
    
    private void initializeDefaults() {
        tvMeditationStatus.setText("准备开始冥想");
        tvNoiseStatus.setText("选择白噪音类型");
        tvBreathingInstruction.setText("点击开始呼吸练习");
        
        // 设置初始状态
        updateTimerDisplay(meditationDurationMs);
        updatePlayPauseButton();
    }
    
    // 冥想计时器相关方法
    private void updateTimerDuration(int minutes) {
        meditationDurationMs = minutes * 60 * 1000L;
        remainingTimeMs = meditationDurationMs;
        tvTimerDuration.setText(minutes + "分钟");
        updateTimerDisplay(meditationDurationMs);
    }
    
    private void startMeditationTimer() {
        isTimerRunning = true;
        isTimerPaused = false;
        tvMeditationStatus.setText("冥想进行中...");
        
        meditationTimer = new CountDownTimer(remainingTimeMs, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                remainingTimeMs = millisUntilFinished;
                updateTimerDisplay(millisUntilFinished);
            }
            
            @Override
            public void onFinish() {
                onMeditationComplete();
            }
        };
        
        meditationTimer.start();
        updatePlayPauseButton();
        startBreathingAnimation();
    }
    
    private void pauseMeditationTimer() {
        if (meditationTimer != null) {
            meditationTimer.cancel();
        }
        isTimerPaused = true;
        tvMeditationStatus.setText("冥想已暂停");
        updatePlayPauseButton();
        stopBreathingAnimation();
    }
    
    private void resumeMeditationTimer() {
        isTimerPaused = false;
        tvMeditationStatus.setText("冥想进行中...");
        startMeditationTimer(); // 重新开始计时器
        startBreathingAnimation();
    }
    
    private void stopMeditationTimer() {
        if (meditationTimer != null) {
            meditationTimer.cancel();
            meditationTimer = null;
        }
        
        isTimerRunning = false;
        isTimerPaused = false;
        remainingTimeMs = meditationDurationMs;
        
        tvMeditationStatus.setText("冥想已停止");
        updateTimerDisplay(meditationDurationMs);
        updatePlayPauseButton();
        stopBreathingAnimation();
    }
    
    private void onMeditationComplete() {
        isTimerRunning = false;
        isTimerPaused = false;
        
        tvMeditationStatus.setText("冥想完成！");
        updatePlayPauseButton();
        stopBreathingAnimation();
        
        // 显示完成提示
        Toast.makeText(requireContext(), "恭喜！冥想完成", Toast.LENGTH_LONG).show();
        
        // 重置计时器
        remainingTimeMs = meditationDurationMs;
        updateTimerDisplay(meditationDurationMs);
    }
    
    private void updateTimerDisplay(long timeMs) {
        long minutes = timeMs / 60000;
        long seconds = (timeMs % 60000) / 1000;
        tvMeditationTime.setText(String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
    }
    
    private void updatePlayPauseButton() {
        if (!isTimerRunning) {
            fabStartPause.setImageResource(android.R.drawable.ic_media_play);
        } else if (isTimerPaused) {
            fabStartPause.setImageResource(android.R.drawable.ic_media_play);
        } else {
            fabStartPause.setImageResource(android.R.drawable.ic_media_pause);
        }
    }
    
    // 白噪音相关方法
    private void updateVolumeLevel(float volume) {
        int percentage = Math.round(volume * 100);
        tvVolumeLevel.setText(percentage + "%");
    }
    
    @Override
    public void onStateChanged(WhiteNoisePlayer.PlayState newState) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                switch (newState) {
                    case PLAYING:
                        btnPlayPause.setText("暂停");
                        tvNoiseStatus.setText("正在播放: 雨声");
                        break;
                    case PAUSED:
                        btnPlayPause.setText("播放");
                        tvNoiseStatus.setText("已暂停: 雨声");
                        break;
                    case STOPPED:
                        btnPlayPause.setText("播放");
                        tvNoiseStatus.setText("已停止");
                        break;
                    case LOADING:
                        btnPlayPause.setText("加载中...");
                        tvNoiseStatus.setText("正在加载雨声...");
                        break;
                }
            });
        }
    }
    
    @Override
    public void onError(String error) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                tvNoiseStatus.setText("播放错误");
                btnPlayPause.setText("播放");
            });
        }
    }
    
    // 呼吸练习相关方法
    private void startBreathingExercise() {
        isBreathingActive = true;
        breathingCycle = 0;
        btnStartBreathing.setText("停止练习");
        
        startBreathingCycle();
    }
    
    private void stopBreathingExercise() {
        isBreathingActive = false;
        btnStartBreathing.setText("开始练习");
        tvBreathingInstruction.setText("点击开始呼吸练习");
        
        if (breathingTimer != null) {
            breathingTimer.cancel();
        }
        
        if (breathingAnimator != null) {
            breathingAnimator.cancel();
        }
    }
    
    private void startBreathingCycle() {
        if (!isBreathingActive) return;
        
        String[] instructions = {"深吸气...", "屏住呼吸...", "慢慢呼气...", "放松..."};
        int[] durations = {4000, 2000, 6000, 2000}; // 毫秒
        
        if (breathingCycle >= instructions.length) {
            breathingCycle = 0;
        }
        
        tvBreathingInstruction.setText(instructions[breathingCycle]);
        
        breathingTimer = new CountDownTimer(durations[breathingCycle], 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 可以在这里更新进度指示器
            }
            
            @Override
            public void onFinish() {
                breathingCycle++;
                startBreathingCycle();
            }
        };
        
        breathingTimer.start();
    }
    
    // 动画相关方法
    private void startBreathingAnimation() {
        if (ivBreathingGuide != null) {
            Animation breathingAnim = AnimationUtils.loadAnimation(requireContext(), 
                    android.R.anim.fade_in);
            breathingAnim.setDuration(4000);
            breathingAnim.setRepeatCount(Animation.INFINITE);
            breathingAnim.setRepeatMode(Animation.REVERSE);
            ivBreathingGuide.startAnimation(breathingAnim);
        }
    }
    
    private void stopBreathingAnimation() {
        if (ivBreathingGuide != null) {
            ivBreathingGuide.clearAnimation();
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        
        // 清理资源
        if (meditationTimer != null) {
            meditationTimer.cancel();
        }
        
        if (breathingTimer != null) {
            breathingTimer.cancel();
        }
        
        if (breathingAnimator != null) {
            breathingAnimator.cancel();
        }
        
        stopBreathingExercise();
        
        if (whiteNoisePlayer != null) {
            whiteNoisePlayer.stop();
            whiteNoisePlayer.setPlaybackListener(null);
        }
    }
} 